<template>
	<view class="login">
		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<image :src="user.avatar | absUrl" mode="widthFix"></image>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<wInput v-model="account" type="text" maxlength="20" placeholder="用户名"></wInput>
				<wInput v-model="password" type="password" maxlength="20" placeholder="密码"></wInput>
			</view>
			<wButton text="登 录" :rotate="isRotate" @click.native="bindLogin()"></wButton>
			
			<!-- 其他登录 -->
			<!-- #ifdef MP-WEIXIN -->
			<view class="other_login cuIcon">
				<view class="other_login_title">
					微信登录
				</view>
				<view class="oauth-row" v-if="hasProvider">
					<view class="oauth-image" v-for="provider in providerList" :key="provider.value">
						<image :src="provider.image"></image>
						<button open-type="getUserInfo" @getuserinfo="oauth"></button>
					</view>
				</view>
			</view>
			<!-- #endif -->
		</view>
		<uni-popup ref="popup" :maskClick="false" type="bottom">
			<view class="pop">
				<view class="pop-title">
					获取头像、昵称用于完善信息
				</view>
				<view class="pop-content">
					<view class="pop-avatar">
						<open-data type="userAvatarUrl"></open-data>
					</view>
					<view class="pop-nick">
						<open-data type="userNickName"></open-data>
					</view>
					
				</view>
				<button class="pop-btn" @click="getUserPro" type="primary">确定</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Util from '../../lib/util.js';
	var WXBizDataCrypt = require('../../lib/cryptojs/RdWXBizDataCrypt.js');
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import wInput from '../../components/watch-login/watch-input.vue' //input
	import wButton from '../../components/watch-login/watch-button.vue' //button

	export default {
		components: {
			wInput,
			wButton
		},
		data() {
			return {
				//logo图片 base64
				providerList: [],
				hasProvider: false,
				positionTop: 0,
				isDevtools: false,
				isRotate: false, //是否加载旋转
				sessionKey:'',
				account:'',
				password: ''
			}
		},
		computed: {
			user() {
				return this.$store.state.session.user;
			},
			forcedLogin() {
				return this.$store.state.session.forcedLogin;
			}
		},
		methods: {
			...mapMutations(['session/login']),
			initProvider() {
				const filters = ['weixin'];
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (res.provider && res.provider.length) {
							for (let i = 0; i < res.provider.length; i++) {
								if (~filters.indexOf(res.provider[i])) {
									this.providerList.push({
										value: res.provider[i],
										image: '../../static/' + res.provider[i] + '.png'
									});
								}
							}
							this.hasProvider = true;
						}
					},
					fail: (err) => {
						console.error('获取服务供应商失败：' + JSON.stringify(err));
					}
				});
			},
			initPosition() {
				/**
				 * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
				 * 反向使用 top 进行定位，可以避免此问题。
				 */
				this.positionTop = uni.getSystemInfoSync().windowHeight - 200;
			},
			bindLogin() {
				/**
				 * 客户端对账号信息进行一些必要的校验。
				 * 实际开发中，根据业务需要进行处理，这里仅做示例。
				 */
				if (this.account.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '请输入账号'
					});
					return;
				}
				if (this.password.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '请输入密码'
					});
					return;
				}
				
				const data = {
					userNameOrEmailAddress: this.account,
					password: this.password,
					rememberMe: true
				};
				this.isRotate = true;
				this.$http.post("/api/TokenAuth/Authenticate", data).then(rep => {
					//console.log(rep.data.result.accessToken);
					this.isRotate = false;
					this.toMain(rep.data.result.accessToken);
				}).catch(_=>{
					this.isRotate = false;
				});
			},
			oauth(e) {
				// uni.getUserProfile({
				// 	desc: '用于完善会员资料',
				// 	success(ru) {
				// 		console.log(ru);
				// 	}
				// });
				// return;
				let self = this;
				let tempName = e.detail.userInfo.nickName;
				uni.login({
					provider: 'weixin',
					success: (res) => {
						var data = e.detail.userInfo;
						const loginModel = {
							nickName: data.nickName,
							avatar: data.avatarUrl,
							jsCode: res.code
						};
						console.log(loginModel);
						self.$http.post("/api/TokenAuth/MiniAppAuthenticate", loginModel)
						.then(replogin => {
							
							self.toMain(replogin.data.result.accessToken);
						});
					},
					fail: (err) => {
						console.error('授权登录失败：' + JSON.stringify(err));
					}
				});
			},
			async toMain(accessToken) {
				this.$store.commit('session/login', accessToken);
				await this.$store.dispatch('session/init');
				
				if (this.$store.state.session.user.name == '微信用户') {
					this.$refs.popup.open();
				} else {
					/**
					 * 强制登录时使用reLaunch方式跳转过来
					 * 返回首页也使用reLaunch方式
					 */
					if (this.forcedLogin) {
						uni.reLaunch({
							url: '../index/index'
						});
					} else {
						uni.navigateBack();
					}
				}
			},
			getUserPro(){
				let self = this;
				uni.getUserProfile({
					desc: '用于完善会员资料',
					success(ru) {
						// console.log(ru);
						let postData = {
							avatar: ru.userInfo.avatarUrl,
							nickName: ru.userInfo.nickName
						};
						self.$http.put('/api/services/app/User/UpdateAvatarAndNickName',postData)
						.then(async res=>{
							await self.$store.dispatch('session/init');
							uni.navigateBack({
								delta:1
							})
						})
					},
					fail() {
						uni.navigateBack({
							delta:1
						})
					}
				})
			}
		},
		onReady() {
			this.initPosition();
			this.initProvider();
			// #ifdef MP-WEIXIN
			this.isDevtools = uni.getSystemInfoSync().platform === 'devtools';
			// #endif

		}
	}
</script>

<style lang="scss">
	@import url("../../components/watch-login/css/icon.css");
	@import url("./css/main.css");
	page{
		background-color: #FFFFFF;
	}
	.header {
		padding: 45rpx 0;
	}

	.header image {
		display: block;
		margin: 0 auto;
		width: 300rpx;
	}
	.btn-container {
		padding: 16rpx 70rpx;
	}
	.login-btn {
	}
	.xieyi {
		display: flex;
		flex-wrap: nowrap;
		padding-left: 60rpx;
		margin-top: 28rpx;
		align-items: center;
	}
	.xieyi label,.xieyi label checkbox {
		margin: 0;
		padding: 0;
	}
	.xieyi .xieyi-text {
		font-size: 24rpx;
		line-height: 1;
	}
	.xieyi .xieyi-text text {
		color: #33b354;
	}
	.oauth-row {
		display: flex;
		flex-direction: row;
		justify-content: center;
		width: 100%;
	}

	.oauth-image {
		position: relative;
		width: 50px;
		height: 50px;
		border: 1px solid #dddddd;
		border-radius: 50px;
		margin: 0 20px;
		background-color: #ffffff;
	}

	.oauth-image image {
		width: 30px;
		height: 30px;
		margin: 10px;
	}

	.oauth-image button {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
	}
	.popbtn{
		background-color: #02b41e;
		color: #ffffff;
		border-radius: 80rpx;
	}
.pop {
	background-color: #FFFFFF;
	padding: 28rpx;
	font-size: 14px;
	.pop-title {
		color: $uni-color-success;
	}
	.pop-content {
		padding: 16rpx;
		display: flex;
		flex-wrap: nowrap;
		align-items: flex-start;
		.pop-avatar {
			width: 100rpx;
			height: 100rpx;
		}
		.pop-nick {
			flex-grow: 1;
			padding-left: 16rpx;
		}
	}
	.pop-btn {
		//background-color: $uni-color-primary;
		line-height: 2;
		margin: 28rpx auto;
	}
}
</style>
